package main

import (
	"flag"
	"github.com/morgine/log"
	"github.com/morgine/pkg/config"
	"github.com/morgine/pkg/redis"
	"market/internal"
	"os"
	"os/signal"
	"syscall"
)

type Configs struct {
	Coins []string `toml:"coins"`
}

func main() {
	// 加载配置文件
	configFile := flag.String("c", "config.toml", "配置文件")
	flag.Parse()

	// 初始化配置服务
	configs, err := config.UnmarshalFile(*configFile)
	if err != nil {
		panic(err)
	}
	client, err := redis.NewClient("redis", configs)
	if err != nil {
		panic(err)
	}
	defer client.Close()

	cfgs := &Configs{}

	err = configs.UnmarshalSub("subscribe", cfgs)
	if err != nil {
		panic(err)
	}
	storage := internal.NewRedisStorage(client)
	cancel := internal.Subscribe(cfgs.Coins, func(flows []*internal.Flow) {
		for _, flow := range flows {
			storage.SaveFlow(flow.Coin, flow)
		}
	})
	defer cancel()
	quit := make(chan os.Signal)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Init.Println("shutting down...")
	defer func() {
		log.Info.Println("done")
	}()
}
